#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
HiAgent Workspace API

Provides endpoints for user workspace management
"""

from fastapi import APIRouter, HTTPException, status, Query, Path
from pydantic import BaseModel, Field
from typing import Dict, Any, Optional
import logging

from src.llm.hiagent_app.utils.api_client import HiAgentAPIClient

logger = logging.getLogger(__name__)

router = APIRouter(
    prefix="/api/v1/hiagent/workspace",
    tags=["HiAgent Workspace"]
)


# Pydantic models
class WorkspaceByUsernameResponse(BaseModel):
    """Response model for getting workspace by username"""
    username: str = Field(..., description="Username")
    user_id: str = Field(..., description="User ID")
    workspace_id: str = Field(..., description="Personal workspace ID")

    class Config:
        json_schema_extra = {
            "example": {
                "username": "2019010471",
                "user_id": "d2sekbnn4eebed08tnig",
                "workspace_id": "personal-d2sekbnn4eebed08tnig"
            }
        }


class UserInfoResponse(BaseModel):
    """Response model for user information"""
    id: str = Field(..., alias="ID", description="User ID")
    username: str = Field(..., alias="UserName", description="Username")
    display_name: Optional[str] = Field(None, alias="DisplayName", description="Display name")
    tenant_id: Optional[str] = Field(None, alias="TenantID", description="Tenant ID")
    email: Optional[str] = Field(None, alias="Email", description="Email")
    status: Optional[int] = Field(None, alias="Status", description="User status")

    class Config:
        populate_by_name = True
        json_schema_extra = {
            "example": {
                "ID": "d2sekbnn4eebed08tnig",
                "UserName": "2019010471",
                "DisplayName": "2019010471",
                "TenantID": "d2rsq5jiih95c30a3p9g",
                "Email": "****",
                "Status": 1
            }
        }


@router.get(
    "/by-username",
    response_model=WorkspaceByUsernameResponse,
    summary="Get workspace ID by username",
    description="Retrieve personal workspace ID for a given username. "
                "The workspace ID follows the pattern: personal-{UserID}",
    responses={
        200: {
            "description": "Successfully retrieved workspace ID",
            "content": {
                "application/json": {
                    "example": {
                        "username": "2019010471",
                        "user_id": "d2sekbnn4eebed08tnig",
                        "workspace_id": "personal-d2sekbnn4eebed08tnig"
                    }
                }
            }
        },
        404: {
            "description": "User not found or workspace not found",
            "content": {
                "application/json": {
                    "example": {
                        "detail": "User not found: username123"
                    }
                }
            }
        },
        500: {
            "description": "Internal server error",
            "content": {
                "application/json": {
                    "example": {
                        "detail": "Failed to retrieve workspace ID"
                    }
                }
            }
        }
    }
)
async def get_workspace_by_username(
    username: str = Query(
        ...,
        description="Username to query",
        min_length=1,
        max_length=100,
        example="2019010471"
    )
) -> WorkspaceByUsernameResponse:
    """
    Get personal workspace ID by username

    This endpoint retrieves the personal workspace ID for a given username.
    The workspace ID typically follows the pattern: personal-{UserID}

    Args:
        username: The username to query

    Returns:
        WorkspaceByUsernameResponse containing username, user_id, and workspace_id

    Raises:
        HTTPException: If user not found or workspace retrieval fails
    """
    try:
        logger.info(f"Getting workspace ID for username: {username}")

        # Create API client
        client = HiAgentAPIClient()

        # Get user information first
        user = client.get_user_by_name(username)
        user_id = user.get('ID')

        logger.info(f"User found - UserID: {user_id}, UserName: {user.get('UserName')}")

        # Get workspace ID
        workspace_id = client.get_workspace_by_username(username)

        logger.info(f"Workspace found - WorkspaceID: {workspace_id}")

        return WorkspaceByUsernameResponse(
            username=username,
            user_id=user_id,
            workspace_id=workspace_id
        )

    except Exception as e:
        error_message = str(e)
        logger.error(f"Failed to get workspace by username '{username}': {error_message}")

        # Determine appropriate status code
        if "not found" in error_message.lower():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=error_message
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to retrieve workspace ID: {error_message}"
            )


@router.get(
    "/user/{username}",
    response_model=UserInfoResponse,
    summary="Get user information by username",
    description="Retrieve user information for a given username",
    responses={
        200: {
            "description": "Successfully retrieved user information"
        },
        404: {
            "description": "User not found"
        },
        500: {
            "description": "Internal server error"
        }
    }
)
async def get_user_info(
    username: str = Path(
        ...,
        description="Username to query",
        min_length=1,
        max_length=100,
        example="2019010471"
    )
) -> UserInfoResponse:
    """
    Get user information by username

    This endpoint retrieves detailed user information for a given username.

    Args:
        username: The username to query

    Returns:
        UserInfoResponse containing user details

    Raises:
        HTTPException: If user not found or retrieval fails
    """
    try:
        logger.info(f"Getting user information for username: {username}")

        # Create API client
        client = HiAgentAPIClient()

        # Get user information
        user = client.get_user_by_name(username)

        logger.info(f"User found - UserID: {user.get('ID')}")

        return UserInfoResponse(**user)

    except Exception as e:
        error_message = str(e)
        logger.error(f"Failed to get user info for '{username}': {error_message}")

        if "not found" in error_message.lower():
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=error_message
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to retrieve user information: {error_message}"
            )


@router.get(
    "/health",
    summary="Health check for workspace service",
    description="Check if the workspace service is running properly"
)
async def health_check() -> Dict[str, str]:
    """
    Health check endpoint

    Returns:
        Dict with status information
    """
    return {
        "status": "healthy",
        "service": "HiAgent Workspace API"
    }
